package cn.bjxy.javaks.store_ms.service;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.util.Properties;

import cn.bjxy.javaks.store_ms.dao.ILogDao;
import cn.bjxy.javaks.store_ms.dao.LogDaoImpl;
import cn.bjxy.javaks.store_ms.entity.AdminEntity;
import cn.bjxy.javaks.store_ms.entity.GoodsEntity;
import cn.bjxy.javaks.store_ms.entity.LogEntity;
import cn.bjxy.javaks.store_ms.utils.StoreMSysUtil;

/**
 * 日志处理类，实现了InvocationHandler接口
 * 
 * @author long
 *
 */
public class LogInvocationHandler implements InvocationHandler {

	private ILogDao logDao = new LogDaoImpl();
	private IAdminService adminService = new AdminServiceImpl();
	private IGoodsService goodsService = new GoodsServiceImpl();

	private Object realObj;
	private Properties pro = new Properties();
	private final static String ADD = "add", DELETE = "delete", MODIFY = "modify", ADMIN = "admin", GOODS = "Goods";
	private static String user;

	public static void setUser(String user) {
		LogInvocationHandler.user = user;
	}

	public LogInvocationHandler(Object realObj) {
		this.realObj = realObj;
		pro.setProperty(ADD, "添加");
		pro.setProperty(MODIFY, "修改");
		pro.setProperty(DELETE, "删除");
		pro.setProperty(ADMIN, "管理员");
		pro.setProperty(GOODS, "货物");
	}

	@Override
	public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

		LogEntity log = new LogEntity();
		String operateType = method.getName();
		// 因为删除之后就取不到操作的对象的数据，所以放在执行前获取
		if (DELETE.equals(method.getName())) {
			if (realObjIsGoods()) {
				log.setContent(pro.getProperty(operateType) + "了" + goodsService.findById((String) args[0]).getLog());
			} else {
				log.setContent(pro.getProperty(operateType) + "了" + adminService.findById((String) args[0]).getLog());
			}
		}

		// 调用目标类中的方法（核心代码）
		Object invoke = method.invoke(realObj, args);

		// 处理日志记录
		if (ADD.equals(operateType) || MODIFY.equals(operateType) || DELETE.equals(operateType)) {
			log.setId(StoreMSysUtil.generateShortUuid());
			log.setOperate_obj(realObjIsGoods() ? pro.getProperty(GOODS) : pro.getProperty(ADMIN));
			log.setAdmin_name(user);
			log.setOperate_type(pro.getProperty(operateType));
			// 获取操作目标的id号
			Object operateId = args[0];
			if (ADD.equals(operateType) || MODIFY.equals(operateType)) {
				if (realObjIsGoods()) {
					log.setOperate_obj_id(((GoodsEntity) operateId).getId());
					log.setContent(pro.getProperty(operateType) + "了"
							+ goodsService.findById(((GoodsEntity) args[0]).getId()).getLog());
				} else {
					log.setOperate_obj_id(((AdminEntity) operateId).getId());
					log.setContent(pro.getProperty(operateType) + "了"
							+ adminService.findById(((AdminEntity) args[0]).getId()).getLog());
				}
			} else {
				log.setOperate_obj_id((String) operateId);
			}
			logDao.add(log);
		}
		return invoke;
	}

	private boolean realObjIsGoods() {
		return realObj.getClass().getSimpleName().contains(GOODS);
	}
}
